Skip to main content

05 修饰器模式

Python 的 Decorator

用了函数式编程的一个技术:用一个函数来构造另一个函数。

def hello(fn):
def wrapper():
print "hello, %s" % fn.__name__
fn()
print "goodbye, %s" % fn.__name__
return wrapper

@hello
def Say():
print "i am Joson"

Hao()


$ python hello.py
hello, Say
i am Joson
goodbye, Say

@注解语法糖(Syntactic sugar)

@decorator
def func():
pass


func = decorator(func)

Go 语言的 Decorator

package main

import "fmt"

func decorator(f func(s string)) func(s string) {
return func(s string) {
fmt.Println("Started")
f(s)
fmt.Println("Done")
}
}

func Hello(s string) {
fmt.Println(s)
}

func main() {
decorator(Hello)("Hello, World!")
}

动用了一个高阶函数 decorator(),在调用的时候,先把 Hello() 函数传进去,然后其返回一个匿名函数。这个匿名函数中除了运行了自己的代码,也调用了被传入的 Hello() 函数。